<template>
  <div id="viewQuestionView">
    <a-row :gutter="[24, 24]">
      <a-col :md="12" :xs="24">
        <a-tabs default-active-key="question">
          <a-tab-pane key="question" title="题目">
            <a-card v-if="question" :title="question.title">
              <a-descriptions
                title="判题条件"
                :column="{ xs: 1, md: 2, lg: 3 }"
              >
                <a-descriptions-item label="时间限制">
                  {{ question.judgeConfig.timeLimit ?? 0 }}
                </a-descriptions-item>
                <a-descriptions-item label="内存限制">
                  {{ question.judgeConfig.memoryLimit ?? 0 }}
                </a-descriptions-item>
                <a-descriptions-item label="堆栈限制">
                  {{ question.judgeConfig.stackLimit ?? 0 }}
                </a-descriptions-item>
              </a-descriptions>
              <MdViewer :value="question.content || ''" />
              <template #extra>
                <a-space wrap>
                  <a-tag
                    v-for="(tag, index) of question.tags"
                    :key="index"
                    color="green"
                    >{{ tag }}
                  </a-tag>
                </a-space>
              </template>
            </a-card>
          </a-tab-pane>
          <a-tab-pane key="comment" title="评论" disabled> 评论区</a-tab-pane>
          <a-tab-pane key="answer" title="题解">
            <div class="answer-header">
              <span class="answer-action">
                <icon-pen />
                <button @click="navigateToAnswerPage(props.id)">写题解</button>
              </span>
            </div>

            <a-list
              :data="solutions"
              :pagination-props="{
                current: solutionParams.current,
                pageSize: solutionParams.pageSize,
                total: solutionTotal,
              }"
              @page-change="onPageChangeSolution"
            >
              <template #item="{ item }">
                <a-list-item
                  class="list-item-type"
                  action-layout="vertical"
                  @click="showSolutionDetail(item)"
                >
                  <a-list-item-meta class="solution-meta">
                    <template #avatar>
                      <a-avatar
                        shape="circle"
                        :imageUrl="item.user?.userAvatar"
                      />
                    </template>
                    <template #title>
                      <span v-if="item.user.userRole === 'admin'">
                        {{ item.user?.userName
                        }}<a-tag color="orange">官方</a-tag>
                      </span>
                      <span v-else>
                        {{ item.user?.userName }}
                      </span>
                    </template>
                    <template #description>
                      <div class="list-item-description">
                        {{ item.content.slice(0, 30) + "..." }}
                      </div>
                    </template>
                  </a-list-item-meta>
                  <template #actions>
                    <span><icon-heart />{{ item.thumbNum }}</span>

                    <span><icon-star />{{ item.favourNum }}</span>

                    <span><icon-message />{{ item.commentNum }}</span>
                  </template>
                </a-list-item>
              </template>
            </a-list>
            <a-modal
              v-model:visible="showSolutionModal"
              title="题解详情"
              @ok="showSolutionModal = false"
              @cancel="showSolutionModal = false"
            >
              <md-preview :modelValue="fullSolutionContent" />
            </a-modal>
          </a-tab-pane>
          <a-tab-pane key="submit" title="提交记录">
            <div v-if="question?.submitNum" class="submitRecord">
              <a-table
                :ref="tableRef"
                :columns="columns"
                :data="dataList"
                :pagination="{
                  showTotal: true,
                  pageSize: searchParams.pageSize,
                  current: searchParams.current,
                  total,
                }"
                @page-change="onPageChange"
              >
                <template #judgeInfo="{ record }">
                  <span :class="judgeClass(record.judgeInfo.message)">
                    {{ record.judgeInfo.message }}
                  </span>
                </template>
                <template #executeTime="{ record }">
                  <icon-schedule />
                  {{
                    record.judgeInfo.time
                      ? record.judgeInfo.time + " ms"
                      : "N/A"
                  }}
                </template>
                <template #executeMemory="{ record }">
                  <icon-bug />
                  {{
                    record.judgeInfo.memory
                      ? record.judgeInfo.memory + " KB"
                      : "N/A"
                  }}
                </template>
                <template #createTime="{ record }">
                  {{ moment(record.createTime).format("YYYY-MM-DD") }}
                </template>
                <template #operations="{ record }">
                  <div class="details-link">
                    <icon-find-replace />
                    <a-space>
                      <a @click="showSubmitDetail(record)">详情</a>
                    </a-space>
                  </div>
                </template>
              </a-table>
            </div>
            <div v-else class="submitRecord">
              <div class="submitPhoto">
                <img src="../../assets/null_light.png" />
              </div>
              <div class="description">暂无数据</div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-col>
      <a-col :md="12" :xs="24">
        <a-form :model="form" layout="inline">
          <a-form-item
            field="language"
            label="编程语言"
            style="min-width: 240px"
          >
            <a-select
              v-model="form.language"
              :style="{ width: '320px' }"
              placeholder="选择编程语言"
            >
              <a-option>java</a-option>
              <a-option>cpp</a-option>
              <a-option>go</a-option>
              <a-option>html</a-option>
            </a-select>
          </a-form-item>
        </a-form>
        <CodeEditor
          :value="form.code"
          :language="form.language"
          :handle-change="changeCode"
        />
        <a-divider size="0" />
        <a-button type="primary" style="min-width: 200px" @click="doSubmit">
          提交代码
        </a-button>
      </a-col>
    </a-row>
    <a-modal
      v-model:visible="showSubmitModal"
      title="提交详情"
      @ok="showSubmitModal = false"
      @cancel="showSubmitModal = false"
    >
      <div>
        <a-descriptions title="提交信息" :column="{ xs: 1, sm: 2, md: 3 }">
          <a-descriptions-item label="提交时间">
            {{ moment(submitDetail.createTime).format("YYYY-MM-DD HH:mm:ss") }}
          </a-descriptions-item>
          <a-descriptions-item label="编程语言">
            <a-tag>{{ submitDetail.language }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="判题信息">
            <span :class="judgeClass(submitDetail.submitStatus)">
              {{ submitDetail.submitStatus }}
            </span>
          </a-descriptions-item>
        </a-descriptions>
        <md-preview
          :modelValue="formattedCode"
          :language="submitDetail.language"
          :editorId="MdId"
        />
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect, withDefaults, defineProps } from "vue";
import message from "@arco-design/web-vue/es/message";
import CodeEditor from "@/components/CodeEditor.vue";
import MdViewer from "@/components/MdViewer.vue";
import {
  QuestionControllerService,
  QuestionSolution,
  QuestionSolutionQueryRequest,
  QuestionSubmitAddRequest,
  QuestionSubmitQueryRequest,
  QuestionVO,
  UserControllerService,
  UserVO,
} from "../../../generated";
import moment from "moment/moment";
import { MdPreview } from "md-editor-v3";
import "md-editor-v3/lib/preview.css";
import { useRouter } from "vue-router";

interface Props {
  id: string;
  answer: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: () => "",
});

const question = ref<QuestionVO>();
const searchParams = ref<QuestionSubmitQueryRequest>({
  questionId: undefined,
  language: undefined,
  pageSize: 10,
  current: 1,
});
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};
const loadQuestionVO = async () => {
  const res = await QuestionControllerService.getQuestionVoByIdUsingGet(
    props.id as any
  );
  if (res.code === 0) {
    question.value = res.data;
  } else {
    message.error("加载失败，" + res.message);
  }
};

const form = ref<QuestionSubmitAddRequest>({
  language: "java",
  code:
    "public class Main {\n" +
    "    public static void main(String[] args) {\n" +
    "\n" +
    "\n" +
    "\n" +
    "\n" +
    "    }\n" +
    "}",
});

/**
 * 提交代码
 */
const doSubmit = async () => {
  if (!question.value?.id) {
    return;
  }

  //提交表单中的代码等信息
  const res = await QuestionControllerService.doQuestionSubmitUsingPost({
    ...form.value,
    questionId: question.value.id,
  });
  if (res.code === 0) {
    message.success("提交成功");
    //提交成功，刷新提交列表
    // await loadSubmitData();
  } else {
    message.error("提交失败," + res.message);
  }
};

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadSubmitData();
  loadUserData();
  loadQuestionVO().then(() => {
    loadSolutions();
  });
});

//提交代码后，更新提交记录
const updateData = () => {
  loadSubmitData();
};

const changeCode = (value: string) => {
  form.value.code = value;
};

/**
 * 定义提交数据的表头信息
 */
const columns = [
  {
    title: "判题信息",
    slotName: "judgeInfo",
  },
  {
    title: "编程语言",
    dataIndex: "language",
  },
  {
    title: "执行用时",
    slotName: "executeTime",
  },
  {
    title: "消耗内存",
    slotName: "executeMemory",
  },
  {
    title: "创建时间",
    slotName: "createTime",
  },
  {
    title: "操作",
    slotName: "operations",
    width: 100,
  },
];
const router = useRouter();
const navigateToAnswerPage = (id: string) => {
  router.push({
    path: `/answer/${id}`,
  });
};

/**
 * 获取当前登录用户的信息
 */
let userId: number | undefined;
const user = ref<UserVO>();

const loadUserData = async () => {
  const res = await UserControllerService.getLoginUserUsingGet();
  if (res.code === 0) {
    userId = res.data?.id;
    user.value = res.data;
  }
};

const tableRef = ref();
const dataList = ref([]);
const total = ref(0);

/**
 * 找寻此问题id、此用户的提交记录
 */
const loadSubmitData = async () => {
  const res = await QuestionControllerService.listQuestionSubmitByPageUsingPost(
    {
      ...searchParams.value,
      questionId: question.value?.id,
      userId: userId,
      sortField: "createTime",
      sortOrder: "descend",
    }
  );
  // console.log("userId为：" + userId);
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadSubmitData();
});

/**
 * 判题信息样式
 */
const judgeClass = (message: string) => {
  if (message === "通过") {
    return "judge-accepted";
  } else return "judge-error";
};

const submitDetail = ref({
  code: "",
  language: "java",
  createTime: "",
  submitStatus: "",
});

const showSubmitModal = ref(false);

const showSubmitDetail = (record: any) => {
  submitDetail.value = {
    code: record.code,
    language: record.language,
    createTime: record.createTime,
    submitStatus: record.judgeInfo.message,
  };
  showSubmitModal.value = true;
};

const MdId = "preview-only";
const formattedCode = ref("");
watchEffect(() => {
  formattedCode.value =
    " ``` " +
    submitDetail.value.language +
    "\n" +
    submitDetail.value.code +
    "\n``` ";
});

/**
 * 获取该题的所有用户题解，并渲染页面
 */
const solutionParams = ref<QuestionSolutionQueryRequest>({
  questionId: props.id as any,
  pageSize: 5,
  current: 1,
});
const solutions = ref<QuestionSolution[]>([]);
const solutionTotal = ref<number>(0);

//从题解返回的userId去获取user对象信息
const fetchUserById = async (userId: number): Promise<UserVO | null> => {
  try {
    const res = await UserControllerService.getUserByIdUsingGet(userId);
    if (res.code === 0) {
      return res.data as UserVO;
    } else {
      message.error("获取用户信息失败，" + res.message);
      return null;
    }
  } catch (error) {
    message.error("获取用户信息出错");
    return null;
  }
};

//获取题解，并根据查询的user和题解信息渲染页面数据
const loadSolutions = async () => {
  const res = await QuestionControllerService.listSolutionByPageUsingPost(
    solutionParams.value
  );
  if (res.code === 0) {
    const solutionData = res.data?.records ?? [];
    solutionTotal.value = res.data?.total ?? 0;

    const promises = solutionData.map(async (solution: QuestionSolution) => {
      const user = await fetchUserById(solution.userId as number);
      return {
        ...solution,
        user: user ?? { userName: "未知用户", userAvatar: "" },
      };
    });
    solutions.value = await Promise.all(promises);
  } else {
    message.error("加载题解失败，" + res.message);
  }
};

/**
 * 题解分页
 * @param page
 */
const onPageChangeSolution = (page) => {
  solutionParams.value.current = page;
  loadSolutions();
};

/**
 *点击用户提交的题解可以查看详细
 */
const showSolutionModal = ref(false);
const fullSolutionContent = ref("");

const showSolutionDetail = async (solution: any) => {
  fullSolutionContent.value = solution.content;
  showSolutionModal.value = true;
};
</script>

<style>
#viewQuestionView {
  max-width: 1400px;
  margin: 0 auto;
}

#viewQuestionView .arco-space-horizontal .arco-space-item {
  margin-bottom: 0 !important;
}

.submitRecord .description {
  text-align: center;
}

.judge-accepted {
  font-weight: bold;
  color: green;
}

.judge-error {
  font-weight: bold;
  color: red;
}

.details-link {
  cursor: pointer;
  color: black;
  transition: color 0.3s;
}

.details-link:hover {
  color: blue;
}

.answer-header {
  background-color: #f0f0f0; /* 灰色背景 */
  padding: 10px;
  display: flex;
  cursor: pointer;
  justify-content: flex-end; /* 右对齐 */
}

.answer-action {
  background-color: green; /* 绿色背景 */
  padding: 5px 10px;
  color: white;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.answer-action button {
  background: none;
  border: none;
  color: white;
  margin-left: 5px;
}
.list-item-type {
  cursor: pointer;
}
</style>
